from flask import Flask, request
from flask_cors import CORS
import json
from dataUtil import sparkConnect
from dataUtil import mongoConnect

app = Flask(__name__)
CORS(app, resources={r'/*'}, supports_credentials=True)


@app.route("/group_analyze", methods=["POST", "GET"])
def group_analyze():
    """
    get the group by the label_id and compute the other labels distribution about this group.

    :request: label info like
        {"label_id":"35203496"}

    :return: A JSON about group info with shape like:
        {"gender":
            {"male":345,
            "female":859},
        "age":
            {"0-10":35,
            "10-20":546}
        ……}
    """
    data = request.args.get("label_ids")
    data = data.split(",")
    print(data)
    # compute group_res
    label_ids_counts = sparkConnect.get_tags_distribution_by_tag_id(data)
    labels_info = mongoConnect.get_labels_by_ids(list(label_ids_counts.keys()))["results"]
    group_res = {}
    print(len(labels_info))
    print(labels_info)
    for label_info in labels_info:
        if label_info["class"] not in list(group_res.keys()):
            group_res[label_info["class"]] = {}
        group_res[label_info["class"]][label_info["name"]] = label_ids_counts[label_info["id"]]
    print(group_res)
    return json.dumps({"group_Info": group_res}, ensure_ascii=False)


@app.route("/indi_profile", methods=["POST", "GET"])
def indi_profile():
    """
    get the labels set of the single item we want.

    :request: item_id like
        {"item_id":"3405273"}

    :return: label list like
        ["male", "19", "student"]
    """
    item_id = request.args.get("user_id")
    tag_ids = sparkConnect.get_tag_ids_by_item_id(item_id)
    print(tag_ids)
    # get label_list
    labels_info = mongoConnect.get_labels_by_ids(tag_ids)["results"]
    label_names = []
    wc_data = []
    for label_info in labels_info:
        print(label_info)
        label_names.append(label_info["name"])
        wc_data.append({"name": label_info["name"], "value": 1})

    label_list = {"name": item_id,
                  "labels": label_names,
                  "label_table": labels_info,
                  "wc_data": wc_data}
    print(label_list)
    return json.dumps(label_list, ensure_ascii=False)


@app.route("/get_topic_list", methods=["Get"])
def get_topic_list():
    topic_list = mongoConnect.get_topic_list()
    print(topic_list)
    re = []
    for cur_topic in topic_list:
        re.append({"value": cur_topic})
    return json.dumps(re, ensure_ascii=False)


if __name__ == "__main__":
    import setproctitle
    setproctitle.setproctitle("bdmo-item")
    app.debug = True
    app.run(host='0.0.0.0', port=5000)
